package net.dass.deadpigeon.server;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Properties;

import javax.mail.Address;
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.google.appengine.repackaged.com.google.common.collect.ImmutableList;

public class MailHandlerServlet extends HttpServlet {

	private static final Message.RecipientType[] RECIPIENT_TYPES = new Message.RecipientType[] {
		Message.RecipientType.TO,
		Message.RecipientType.CC,
		Message.RecipientType.BCC
	};

	public void doPost(HttpServletRequest req, HttpServletResponse resp)
			throws IOException {
		Properties props = new Properties(); 
		Session session = Session.getDefaultInstance(props, null); 
		try {
			final MimeMessage	message			= new MimeMessage(session, req.getInputStream());

			message.setSender(new InternetAddress("", ""));// TODO: use hosting admin account details here 
			message.setSubject("[DeadPigeon]" + message.getSubject());
			for (Message.RecipientType rtype : RECIPIENT_TYPES) {
				final Address[]			mrecipients	= message.getRecipients(rtype);
				final ImmutableList<Address>	recipients	= ImmutableList.copyOf((mrecipients != null) ? mrecipients : new Address[0]);
				final List<DeadPigeon>	pigeons		= getDeadPigeon(recipients);

				for (final DeadPigeon pigeon : pigeons) {
					final Hunter		hunter = getHunterFor(pigeon);
					
					message.setHeader("X-DEADPIGEON-KILLED", "true");
					message.setHeader("Delivered-To", hunter.getEmail());
		            message.setHeader("X-DEADPIGEON-FLOCK", "");
		            Transport.send(message);
		            message.setRecipients(rtype, recipients.toArray(new Address[recipients.size()]));
				}
			}
		} catch (MessagingException e) {
			e.printStackTrace();
		}
	}

	private Hunter getHunterFor(DeadPigeon pigeon) {
		return (new Hunter("", "pigeon hunter")); // Mock Pigeon for now
	}

	private List<DeadPigeon> getDeadPigeon(List<Address> recipients) {
		return (new ArrayList<DeadPigeon>() {{
			this.add(new DeadPigeon(""));
		}}); // Mock Pigeon for now
	}
	
}
